import { HealthRecordModel, type HealthRecord } from "../db/model";

interface GetRecordsOptions {
  recordType?: "weight" | "bloodPressure" | "heartRate" | "sleepQuality";
  startDate?: Date;
  endDate?: Date;
  limit?: number;
  skip?: number;
}

export class HealthService {
  // 获取健康记录列表
  async getRecords(userId: string, options?: GetRecordsOptions) {
    const query: any = { userId };

    if (options?.recordType) {
      query.recordType = options.recordType;
    }

    if (options?.startDate || options?.endDate) {
      query.timestamp = {};
      if (options.startDate) {
        query.timestamp.$gte = options.startDate;
      }
      if (options.endDate) {
        query.timestamp.$lte = options.endDate;
      }
    }

    const [records, total] = await Promise.all([
      HealthRecordModel.find(query)
        .sort({ timestamp: -1 })
        .skip(options?.skip || 0)
        .limit(options?.limit || 20),
      HealthRecordModel.countDocuments(query)
    ]);

    // 获取每种类型的最新记录
    const latestRecords = await this.getLatestRecords(userId);

    return {
      records,
      total,
      latestRecords
    };
  }

  // 创建健康记录
  async createRecord(data: Partial<HealthRecord>) {
    return await HealthRecordModel.create(data);
  }

  // 获取单个健康记录
  async getRecord(userId: string, recordId: string) {
    const record = await HealthRecordModel.findOne({ _id: recordId, userId });
    if (!record) {
      throw new Error("健康记录不存在");
    }
    return record;
  }

  // 更新健康记录
  async updateRecord(userId: string, recordId: string, data: Partial<HealthRecord>) {
    const record = await HealthRecordModel.findOneAndUpdate(
      { _id: recordId, userId },
      { $set: data },
      { new: true }
    );

    if (!record) {
      throw new Error("健康记录不存在");
    }

    return record;
  }

  // 删除健康记录
  async deleteRecord(userId: string, recordId: string) {
    const result = await HealthRecordModel.findOneAndDelete({ _id: recordId, userId });
    if (!result) {
      throw new Error("健康记录不存在");
    }
    return true;
  }

  // 获取最新记录
  private async getLatestRecords(userId: string) {
    const recordTypes = ["weight", "bloodPressure", "heartRate", "sleepQuality"] as const;
    const latestRecords: { [key: string]: HealthRecord | undefined } = {};

    await Promise.all(
      recordTypes.map(async (type) => {
        const record = await HealthRecordModel.findOne({ 
          userId, 
          recordType: type 
        }).sort({ timestamp: -1 });
        
        if (record) {
          latestRecords[type] = record;
        }
      })
    );

    return latestRecords;
  }

  // 获取健康趋势数据
  async getHealthTrends(
    userId: string,
    recordType: "weight" | "bloodPressure" | "heartRate" | "sleepQuality",
    startDate: Date,
    endDate: Date
  ) {
    const records = await HealthRecordModel.find({
      userId,
      recordType,
      timestamp: { $gte: startDate, $lte: endDate }
    }).sort({ timestamp: 1 });

    // 这里可以添加更多的数据处理逻辑，比如计算平均值、趋势等
    return records;
  }
}
